package com.jjh.jhwebserver.context;

import com.jjh.jhwebserver.io.JhOutputStream;
import com.jjh.jhwebserver.io.JhPrintwriter;

import java.io.*;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author JJH
 */
public class HttpServletResponse extends JhResponse{

    /**
     * 状态码
     */
    private int status;
    /**
     * 响应头信息
     */
    private HashMap<String,String> headers = new HashMap<>();
    /**
     * 响应体
     * （主要是html，css，json响应体）
     */
    private String responseBody;

    /**
     * 二进制文件
     */
    private File resFile;

    /**
     * 对响应体那部分要写的内容流
     */
    private JhOutputStream resOutputStream;

    public HttpServletResponse(){}





    /**
     * 打印流
     */
    public PrintWriter getWriter(){
        Writer writer = new OutputStreamWriter(this.resOutputStream);
        return new JhPrintwriter(writer,this.responseBody);
    }

    /**
     * 直接写文本文件（html,js,css,json)
     * @param res  字符串
     */
    public void write(String res){
        this.responseBody = res;
    }

    /**
     * 二进制文件
     * @param file 文件
     */
   public void write(File file){
        this.resFile = file;
   }



    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public HashMap<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(HashMap<String, String> headers) {
        this.headers = headers;
    }


    /**
     * 添加响应头
     * @param header
     */
    public void addHeader(String header){
        String[] str = header.split(":");
        this.headers.put(str[0],str[1]);
    }

    /**
     * 设置响应头，如果有重复的，就覆盖掉
     * @param header
     */
    public void setHeader(String header){
        String[] str = header.split(":");
        this.headers.put(str[0],str[1]);
    }

    /**
     * 根据响应头获取响应头内容
     * @param header 响应头
     * @return 头内容
     */
    public String getHeader(String header){
        AtomicReference<String> str = new AtomicReference<>("");
        this.headers.forEach((head,value)->{
            if(head.equals(header)){
                str.set(value);
            }
        });
        return str.get();
    }

    public String getResponseBody() {
        return responseBody;
    }


    public File getResFile() {
        return resFile;
    }
}
